import requests
from flask import Flask, jsonify, request

app = Flask(__name__)

# 替换为你的DeepSeek API Key
API_KEY = "sk-jicddbvltimsyfbzziogbftqtezmizdvvzwdrplhwyglqjuw"
# DeepSeek API地址
API_BASE = "https://api.deepseek.com/v1"

@app.route('/wechat', methods=['GET', 'POST'])
def wechat():
    if request.method == 'GET':
        # 微信验证服务器配置
        # return verify(request.args)
        response = call_deepseek_api("你好")
        return jsonify(response, 200)
    elif request.method == 'POST':
        # 处理微信消息
        # data = request.xml
        # 提取用户发送的消息内容
        data = request.get_json()
        # 调用DeepSeek API获取回复
        # response = call_deepseek_api(data['Content'])
        response = call_deepseek_api("你好")
        # 回复微信消息

        return jsonify(response), 200
        # return reply(data['FromUserName'], data['ToUserName'], response)

def call_deepseek_api(message):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}"
    }
    data = {
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": message}]
    }
    response = requests.post(f"{API_BASE}/chat/completions", headers=headers, json=data)
    response_data = response.json()

    if 'error' in response_data:
        error_type = response_data['error']['type']
        error_message = response_data['error']['message']
        if error_type == 'unknown_error' and 'Insufficient Balance' in error_message:
            return "抱歉，当前账户余额不足，请充值后再试。"
        else:
            return f"请求出错: {error_message}"
    else:
        print("response_data====",response_data)
        return response_data['choices'][0]['message']['content']
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)